<?php

set_time_limit(0);

require ROOT_PATH.'/Helper/base_abstract.php';


class Action extends base_abstract
{
    function delete($file_id)
    {
        _model('user_files')->delete(array('id'=>$file_id, 'user_id'=>$_SESSION['admin_user']['id']));
    }

    function get($id)
    {
        return _model('user_files')->read(array('id'=>$id));
    }

    function get_list($keywords = '')
    {
        if ($keywords) {
            $keywords = addslashes($keywords);
            $data = _model('user_files')->getList("WHERE user_id = {$_SESSION['admin_user']['id']} AND file_name LIKE '%$keywords%'", new Pager(8));
        } else {
            $data = _model('user_files')->getList(array('user_id'=>$_SESSION['admin_user']['id']), 'ORDER BY add_time DESC', new Pager(8));
        }
        $this->view->assign($data);
        $this->view->display('admin/upload_file.html');
    }

    function index()
    {
        if (empty($_SESSION['admin_user']['id'])) {
            exit('4');
        }
        $file = $_FILES['Filedata'];
        $time = time();
        $ext = end(explode('.', $file['name']));
        $size = filesize($file['tmp_name']);
        $folder = ROOT_PATH.'/upload/'.date('Y/m/d', $time);
        if (!file_exists($folder) && !@mkdir($folder, 0777, true)){
            exit('3');
        }

        $target = $folder.'/'.md5_file($file['tmp_name']).$size.'.'.$ext;
        if (!file_exists($target)) {
            if (!rename($file['tmp_name'], $target)) {
                exit('2');
            }
        }
        chmod($target, 0777);
        $param = array(
            'user_id' => $_SESSION['admin_user']['id'],
            'file_name' => $file['name'],
            'file_path' => substr($target, strlen(ROOT_PATH)+1),
            'file_size' => $size,
            'ext' => strtolower($ext),
            'add_time' => $time
        );

        $id = _model('user_files')->create($param);

        exit('1');
    }
}

?>